package com.company.cloud.web.render;

import com.jfinal.template.Engine;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class TemplateRender extends Render{


    protected static Engine engine;

    private static final String contentType = "text/html; charset=" + getEncoding();

    static void init(Engine engine) {
        if (engine == null) {
            throw new IllegalArgumentException("engine can not be null");
        }
        TemplateRender.engine = engine;
    }

    public TemplateRender(String view) {
        this.view = view;
    }

    public String getContentType() {
        return contentType;
    }

    @Override
    public void render() {
        response.setContentType(getContentType());
        Map<Object, Object> data = new HashMap<Object, Object>();
        for (Enumeration<String> attrs = request.getAttributeNames(); attrs.hasMoreElements();) {
            String attrName = attrs.nextElement();
            data.put(attrName, request.getAttribute(attrName));
        }

        try {
            OutputStream os =response.getOutputStream();
            engine.getTemplate(view).render(data,os);
            os.flush();
        }catch (RuntimeException e){
            Throwable cause = e.getCause();
            if (cause instanceof IOException) {	// ClientAbortException、EofException 直接或间接继承自 IOException
                String name = cause.getClass().getSimpleName();
                if ("ClientAbortException".equals(name) || "EofException".equals(name)) {
                    return ;
                }
            }
            throw e;
        } catch (IOException e) {
            throw new RenderException(e);
        }
    }

    public String toString() {
        return view;
    }
}
